//
//  UITextView+Extension.swift
//  emojiKeyboardDemo
//
//  Created by Jin on 2018/5/18.
//  Copyright © 2018年 Jin. All rights reserved.
//

import UIKit

extension UITextView {
    
    //获取属性字符串
    func getTextViewAttributeString() -> String{
        //创建属性字符串
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        //遍历属性字符串
        let range = NSRange(location: 0, length: attrMStr.length)
        attrMStr.enumerateAttributes(in: range, options: []) { (dict, range, _) in
            if let attchment = dict[NSAttributedStringKey(rawValue: "NSAttachment")] as? EmotionAttachment {
                attrMStr.replaceCharacters(in: range, with: attchment.chs!)
            }
        }
        return attrMStr.string
    }
    
    //插入表情
    func insertEmotionToTextView(emotion:Emotion){
        //空白表情
        if emotion.isEmpty {
            return
        }
        //删除按钮
        if emotion.isRemove {
            deleteBackward()
            return
        }
        //emoji不需要处理图文混排
        if emotion.emojiCode != nil {
            let textRange = selectedTextRange
            replace(textRange!, withText: emotion.emojiCode!)
            return
        }
        
        //普通表情,处理图文混排
        let attachment = EmotionAttachment()
        attachment.image = UIImage(contentsOfFile: emotion.pngPath!)
        attachment.chs = emotion.chs
        let font = self.font!
        attachment.bounds = CGRect(x: 0, y: 0, width: font.lineHeight, height: font.lineHeight)
        let attrImageStr = NSAttributedString(attachment: attachment)
        
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        let range = selectedRange
        attrMStr.replaceCharacters(in: range, with: attrImageStr)
        attributedText = attrMStr
        //将文字大小重置
        self.font = font
        //设置光标回原来位置+1
        selectedRange = NSRange(location: range.location + 1, length: 0)
    }
}
